<?php

namespace Dongasai\WkProtoPhp\Packets;

use Dongasai\WkProtoPhp\Enums\FrameType;
use Dongasai\WkProtoPhp\Framer;
use Dongasai\WkProtoPhp\Encoder;
use Dongasai\WkProtoPhp\Decoder;

/**
 * RECVACK接收回执包
 */
class RecvackPacket extends Framer
{
    private int $messageId = 0;
    private int $messageSeq = 0;

    public function __construct()
    {
        parent::__construct(FrameType::RECVACK->value);
    }

    public function getFrameType(): int
    {
        return FrameType::RECVACK->value;
    }

    public function __toString(): string
    {
        return sprintf(
            'RECVACK MessageId:%d MessageSeq:%d',
            $this->messageId,
            $this->messageSeq
        );
    }

    // Getters and Setters
    public function getMessageId(): int
    {
        return $this->messageId;
    }

    public function setMessageId(int $messageId): void
    {
        $this->messageId = $messageId;
    }

    public function getMessageSeq(): int
    {
        return $this->messageSeq;
    }

    public function setMessageSeq(int $messageSeq): void
    {
        $this->messageSeq = $messageSeq;
    }

    
    /**
     * 解码RECVACK包
     */
    public static function decode(Framer $framer, string $data, int $version): self
    {
        $decoder = new Decoder($data);
        $packet = new self();
        
        // 复制framer属性
        $packet->setRemainingLength($framer->getRemainingLength());
        $packet->setNoPersist($framer->getNoPersist());
        $packet->setRedDot($framer->getRedDot());
        $packet->setSyncOnce($framer->getSyncOnce());
        $packet->setDUP($framer->getDUP());
        $packet->setFrameSize($framer->getFrameSize());

        try {
            // 读取消息ID
            $packet->messageId = $decoder->int64();

            // 读取消息序列号
            $packet->messageSeq = $decoder->uint32();

        } catch (\Exception $e) {
            throw new \RuntimeException('解码RECVACK包失败: ' . $e->getMessage(), 0, $e);
        }

        return $packet;
    }

    /**
     * 编码RECVACK包
     */
    public function encode(Encoder $encoder, int $version): void
    {
        $encoder->writeInt64($this->messageId);
        $encoder->writeUint32($this->messageSeq);
    }

    /**
     * 计算RECVACK包大小
     */
    public function size(int $version): int
    {
        $size = 0;
        $size += 8; // MessageId
        $size += 4; // MessageSeq
        return $size;
    }
}